<?php

namespace App\Http\Controllers\Admin;

use App\Comment;
use App\Message;
use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Article;

class ArticleController extends Controller
{
    //
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view("admin/article/index")->withArticles(Article::all());
    }

    public function create()
    {
        return view('admin/article/create');
    }

    private function verfity(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
            'body' => 'required',
        ]);
    }

    public function store(Request $request)
    {
        $this->verfity($request);

        $parse = new \Parsedown();
        $article = new Article();
        $article->title = $request->get('title');
        $article->body = $parse->text($request->get('body'));
        $article->user_id = $request->user()->id;
        $user = User::where('id', $request->user()->id)->first();
        $article->author = $user['name'];

        if ($article->save())
            return redirect('admin/article');
        else
            return redirect()->back()->withInput()->withErrors("保存失败");
    }

    public function edit($id)
    {
        return view('admin/article/edit')->withArticle(Article::find($id));
    }

    public function update(Request $request, $id)
    {
        $this->verfity($request);

        $parse = new \Parsedown();
        $data['title'] = $request->get('title');
        $data['body'] = $parse->text($request->get('body'));

        $article = new Article();
        if ($article->where('id', $id)->update($data))
            return redirect("admin/article");
        else
            return redirect()->back()->withInput()->withErrors("修改出错");
    }

    public function destroy($id)
    {
        $all = Article::with('hasManyComments')->find($id);
        $allComments = $all['hasManyComments'];
        foreach ($allComments as $comments) {
            Comment::find($comments['id'])->delete();
        }
        Message::where('article_id', $id)->delete();
        Article::find($id)->delete();
        return redirect()->back()->withInput()->withErrors("删除成功");
    }
}
